<?php

namespace App\Http\Controllers;

use App\Models\User;
use App\Service\User\UserService;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Facades\Validator;
use Tymon\JWTAuth\Facades\JWTAuth;
use Tymon\JWTAuth\Exceptions\JWTException;

class AuthController extends Controller
{
    /**
     * 用户注册
     *
     * @param Request $request
     * @return JsonResponse
     */
    public function register (Request $request): JsonResponse
    {
        $validator = Validator::make($request->all(), [
            'phone'    => 'required|string|unique:users',
            'password' => 'required|string|min:6',
        ]);

        if ($validator->fails()) {
            return $this->validationError($validator->errors());
        }

        $user = User::create([
            'name'     => $request->phone,
            'phone'    => $request->phone,
            'password' => Hash::make($request->password),
        ]);

        $token = JWTAuth::fromUser($user);

        return $this->created([
            'user'       => $user,
            'token'      => $token,
            'token_type' => 'bearer',
            // 过期时间设置为30天，单位为秒
            'expires_in' => config('jwt.ttl') * 60
        ], '注册成功');
    }

    /**
     * 用户登录
     *
     * @param Request $request
     * @return JsonResponse
     */
    public function login (Request $request): JsonResponse
    {
        $validator = Validator::make($request->all(), [
            'phone'    => 'required|string|regex:/^1[3-9]\\d{9}$/',
            'password' => 'required|string|min:6',
        ]);

        if ($validator->fails()) {
            return $this->validationError($validator->errors());
        }

        // 手动查找用户并验证密码
        $user = User::where('phone', $request->phone)
                    ->first();

        if (!$user || !Hash::check($request->password, $user->password)) {
            return $this->unauthorized('手机号或密码错误');
        }

        try {
            // 使用用户实例创建令牌
            $token = JWTAuth::fromUser($user);
        } catch (JWTException $e) {
            return $this->error('无法创建令牌');
        }

        return $this->success([
            'user'     => $user,
            'check_in' => UserService::isCheckIn($user->id),
            'level'    => [
                'label'    => $user->achievement,
                'progress' => $user->experience
            ],
            'token'    => $token
        ], '登录成功');
    }

    /**
     * 获取当前用户信息
     *
     * @return JsonResponse
     */
    public function me (): JsonResponse
    {
        $user = Auth::user();
        return $this->success([
            'user'     => $user,
            'check_in' => UserService::isCheckIn($user->id),
            'level'    => [
                'label'    => $user->achievement,
                'progress' => $user->experience
            ]
        ]);
    }

    /**
     * 刷新令牌
     *
     * @return JsonResponse
     */
    public function refresh (): JsonResponse
    {
        try {
            $newToken = JWTAuth::refresh(JWTAuth::getToken());

            return $this->success([
                'token'      => $newToken,
                'token_type' => 'bearer',
                'expires_in' => config('jwt.ttl') * 60
            ], '令牌刷新成功');
        } catch (JWTException $e) {
            return $this->unauthorized('令牌刷新失败');
        }
    }

    /**
     * 用户登出
     * @return JsonResponse
     */
    public function logout (): JsonResponse
    {
        try {
            JWTAuth::invalidate(JWTAuth::getToken());
            return $this->success(null, '登出成功');
        } catch (JWTException $e) {
            return $this->success(null, '登出成功'); // 即使令牌已失效，也认为登出成功
        }
    }

    /**
     * 修改密码
     *
     * @param Request $request
     * @return JsonResponse
     */
    public function changePassword (Request $request): JsonResponse
    {
        $validator = Validator::make($request->all(), [
            'current_password' => 'required|string',
            'new_password'     => 'required|string|min:6|confirmed',
        ]);

        if ($validator->fails()) {
            return $this->validationError($validator->errors());
        }

        $user = JWTAuth::parseToken()
                       ->authenticate();

        if (!Hash::check($request->current_password, $user->password)) {
            return $this->fail('当前密码错误');
        }

        $user->update(['password' => Hash::make($request->new_password)]);

        return $this->success(null, '密码修改成功');
    }

    /**
     * 修改用户信息
     *
     * @param Request $request
     * @return JsonResponse
     */
    public function updateProfile (Request $request): JsonResponse
    {
        $validator = Validator::make($request->all(), [
            'name'     => 'sometimes|required|string|max:128',
            'avatar'   => 'sometimes|required|file|image|mimes:jpeg,jpg,png,gif,webp|max:2048',
            'email'    => 'sometimes|required|string|email|max:255|unique:users,email,' . auth()->id(),
            'gender'   => 'sometimes|required|integer|in:0,1,2',
            'birthday' => 'sometimes|required|string|date_format:Y-m-d',
            'height'   => 'sometimes|required|numeric|between:0,300',
            'target_weight'   => 'sometimes|required|numeric|between:0,500'
        ]);

        // 验证失败处理
        if ($validator->fails()) {
            return $this->validationError($validator->errors());
        }

        // 只更新提交的字段
        $updateData = [];

        $user = JWTAuth::parseToken()
                       ->authenticate();

        // 更新姓名
        if ($request->has('name')) {
            $updateData['name'] = $request->name;
        }

        // 更新头像
        if ($request->hasFile('avatar')) {
            $file = $request->file('avatar');
            // 保存到 storage/app/public/avatar 目录
            $filePath = $file->store('avatar', 'public');
            // 获取可访问的 URL
            $fileUrl = Storage::url($filePath);
            // 这里可以将 $fileUrl 保存到数据库或返回给前端
            $updateData['avatar'] = config('app.url') . $fileUrl;
        }

        // 更新邮箱
        if ($request->has('email')) {
            $updateData['email'] = $request->email;
        }

        // 更新性别
        if ($request->has('gender')) {
            $updateData['gender'] = $request->gender;
        }

        // 更新生日
        if ($request->has('birthday')) {
            $updateData['birthday'] = $request->birthday;
        }

        // 更新身高
        if ($request->has('height')) {
            $updateData['height'] = $request->height;
        }

        // 更新体重
        if ($request->has('target_weight')) {
            $updateData['target_weight'] = $request->target_weight;
        }

        $user->update($updateData);

        return $this->success([
            'user' => $user->fresh()
        ], '用户信息修改成功');
    }


    /**
     * 用户签到
     * @param Request $request
     * @return JsonResponse
     */
    public function checkIn (Request $request): JsonResponse
    {
        $user = Auth::user();

        if (!$user) {
            return $this->error('用户未登录', 401);
        }

        $result = UserService::checkIn($user->id);

        if ($result['success']) {
            return $this->success($result['data'], $result['message']);
        } else {
            return $this->error($result['message'], 400, $result['data']);
        }
    }

    /**
     * 获取用户签到信息
     *
     * @param Request $request
     * @return JsonResponse
     */
    public function getCheckInInfo (Request $request): JsonResponse
    {
        $user = Auth::user();

        if (!$user) {
            return $this->error('用户未登录', 401);
        }

        $checkInInfo = UserService::getCheckInInfo($user->id);

        return $this->success($checkInInfo, '获取签到信息成功');
    }

    /*
     * 成就列表
     */
    public function achievement (Request $request): JsonResponse
    {
        $data = [
            [
                'name' => '炼气期',
                'level' => '1～15层',
                'desc' => '初学修炼，炼化天地灵气,打基础。'
            ], [
                'name' => '筑基期',
                'level' => '初期、中期、后期',
                'desc' => '凝聚灵基，筑稳道基，迈入修真正途。'
            ], [
                'name' => '结丹期',
                'level' => '初期、中期、后期',
                'desc' => '凝结金丹，修为大涨，寿命延长。'
            ], [
                'name' => '元婴期',
                'level' => '初期、中期、后期',
                'desc' => '诞生元婴，神魂离体，灵识大成。'
            ], [
                'name' => '化神期',
                'level' => '初期、中期、后期',
                'desc' => '神魂凝实，神识可化形，可远离肉身。'
            ], [
                'name' => '婴变期',
                'level' => '初期、中期、后期',
                'desc' => '元婴蜕变，力量本质飞跃。'
            ], [
                'name' => '问鼎期',
                'level' => '初期、中期、后期',
                'desc' => '触摸天地法则，问鼎修真巅峰。'
            ], [
                'name' => '阴虚',
                'level' => '初期、中期、后期',
                'desc' => '元神化虚，神魂无形，掌控部分法则。'
            ], [
                'name' => '阳实',
                'level' => '初期、中期、后期',
                'desc' => '虚实转化，肉身与神魂并强，法力极深。'
            ], [
                'name' => '窥涅期',
                'level' => '初期、中期、后期',
                'desc' => '开始触摸涅槃大道，窥探超脱真意。'
            ], [
                'name' => '净涅期',
                'level' => '初期、中期、后期',
                'desc' => '洗涤灵魂，肉身神魂趋于纯净无瑕。'
            ], [
                'name' => '碎涅期',
                'level' => '初期、中期、后期',
                'desc' => '破碎自我，准备重生，踏入真超脱。'
            ], [
                'name' => '天人五衰',
                'level' => '一衰～五衰',
                'desc' => '体悟天命终衰之劫，生死轮回之极限。'
            ], [
                'name' => '空涅期',
                'level' => '初期、中期、后期',
                'desc' => '涅槃至虚空之境，抛却执念，明悟大空。'
            ], [
                'name' => '空灵期',
                'level' => '初期、中期、后期',
                'desc' => '神魂空灵，肉身近无，感悟本源真理。'
            ], [
                'name' => '空玄期',
                'level' => '初期、中期、后期',
                'desc' => '万法归一，悟空之玄妙，规则融心。'
            ], [
                'name' => '空劫期',
                'level' => '初期、中期、后期',
                'desc' => '渡劫空境，命运对决，心念不灭。'
            ], [
                'name' => '大天尊',
                'level' => '大尊、金尊、天尊、跃天尊',
                'desc' => '统御天地之尊，万族敬仰，法则随心。'
            ], [
                'name' => '踏天九桥',
                'level' => '第一桥 ～ 第九桥',
                'desc' => '每桥一悟，踏桥问天，超越极限。'
            ], [
                'name' => '踏天境',
                'level' => '无小境界划分',
                'desc' => '登临终极之境，破界成神，逆天改命。'
            ]
        ];

        return $this->success($data);
    }
}
